package org.sang.service;

import org.apache.log4j.Logger;
import org.sang.bean.DailyReport;
import org.sang.bean.User;
import org.sang.common.UserUtils;
import org.sang.mapper.DailyReportMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service("dailyReportService")
@Transactional
public class DailyReportService  {

	SimpleDateFormat birthdayFormat = new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
    private DailyReportMapper dailyReportMapper;

	public List<DailyReport> getDailyByPage(Integer page, Integer size, String keywords,Long userId, String beginDateScope) {
		int start = (page - 1) * size;
		Date startBeginDate = null;
		Date endBeginDate = null;
		if (beginDateScope != null && beginDateScope.contains(",")) {
			try {
				String[] split = beginDateScope.split(",");
				startBeginDate = birthdayFormat.parse(split[0]);
				endBeginDate = birthdayFormat.parse(split[1]);
			} catch (ParseException e) {
			}
		}
		return dailyReportMapper.getDailyReportByPage(start, size, keywords, userId, startBeginDate, endBeginDate);
	}

	public Long getCountByKeywords(String keywords,Long userId,String beginDateScope) {
		Date startBeginDate = null;
		Date endBeginDate = null;
		if (beginDateScope != null && beginDateScope.contains(",")) {
			try {
				String[] split = beginDateScope.split(",");
				startBeginDate = birthdayFormat.parse(split[0]);
				endBeginDate = birthdayFormat.parse(split[1]);
			} catch (ParseException e) {
			}
		}
		return dailyReportMapper.getCountByKeywords(keywords, userId,startBeginDate, endBeginDate);
	}

	public DailyReport getDailyReportById(String dailyId) {
		return dailyReportMapper.selectByPrimaryKey(dailyId);
	}

	public int addDailyReport(DailyReport dailyReport) {
		User user= UserUtils.getCurrentUser();
		dailyReport.setAuthor(user.getName());
		dailyReport.setUserId(user.getId());
		return dailyReportMapper.insert(dailyReport);
	}
	public boolean delDailyReportById(String ids) {
		String[] split = ids.split(",");
		return dailyReportMapper.delDailyReportById(split) == split.length;
	}

	public int updateDailyReport(DailyReport dailyReport) {
		return dailyReportMapper.updateByPrimaryKeySelective(dailyReport);
	}
}